package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityGoodsList3Binding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.self.GoodsListEntity3;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.swgk.core.util.ACAdminDialogUtils;
import com.sgb.kjwl.view.event.self.GoodsEvent;
import com.sgb.kjwl.view.ui.adapter.self.publish.GoodsListAdapter3;
import com.sgb.kjwl.view.ui.fragment.self.GoodsStateFragment3;
import com.sgb.kjwl.view.widget.CategoryPopWindow3;
import com.sgb.kjwl.view.widget.DictWindow3;
import com.sgb.kjwl.view.widget.DictWindow4;
import com.sgb.kjwl.viewmodel.self.publish.GoodsListModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import static com.swgk.core.event.EventConstant.EVENT_GOODS_PUBLISH;
import static com.swgk.core.event.EventConstant.EVENT_GOODS_PUBLISH_NO_ID;

/**
 * 商品管理
 * @author Administrator
 */
public class GoodsListActivity3 extends AppActivity {
    private ActivityGoodsList3Binding binding;
    public static final String OPT_UP = "1";
    public static final String OPT_DOWN = "2";
    public static final String OPT_DEL = "3";
    private String[] titles = {"已上架", "已下架"};
    private ArrayList<Fragment> mFragments;
    private GoodsStateFragment3 upFragment;
    private GoodsStateFragment3 downFragment;

    private GoodsListAdapter3 goodsListAdapter3;
    @Inject
    GoodsListModel3 viewModel;
    private DictWindow4 allWindow4;
    private CategoryPopWindow3 categoryPopWindow3;
    private List<DictEntity3> allDictEntityList;
    private List<MenuEntity<MenuEntity<MenuEntity>>> categoryList;
    private String allChecked = "";

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, GoodsListActivity3.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(GoodsListActivity3.this, R.layout.activity_goods_list3);
        binding.backView.setOnClickListener(this);
        binding.editView.setOnClickListener(this);
        binding.allLayout.setOnClickListener(this);
        binding.addLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);

        mFragments = new ArrayList<Fragment>();
        upFragment = GoodsStateFragment3.newInstance(GoodsStateFragment3.STATUS_UP);
        downFragment = GoodsStateFragment3.newInstance(GoodsStateFragment3.STATUS_DOWN);
        mFragments.add(upFragment);
        mFragments.add(downFragment);
        SlidingFragmentPagerAdapter mAdapetr = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, titles);
        binding.viewpager.setAdapter(mAdapetr);
        binding.viewpager.setOffscreenPageLimit(1);
        binding.tablayout.setupWithViewPager(binding.viewpager);
        binding.editSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    closeKeybord();
                    viewModel.condition.set(binding.editSearch.getText().toString());
                    viewModel.getGoodsListModel(false);
                }
                return false;
            }
        });
        initGoodsListView();
    }

    private void initGoodsListView() {
        if (goodsListAdapter3 == null) {
            goodsListAdapter3 = new GoodsListAdapter3(GoodsListActivity3.this, null);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(GoodsListActivity3.this);
        binding.rlvList.setLayoutManager(layoutManager);
        binding.rlvList.addItemDecoration(new RecyclerCustomDecoration(0,
                0,
                0,
                getResources().getDimension(R.dimen.dp1), getResources().getColor(R.color.color_F5F5F5)));
        binding.rlvList.setAdapter(goodsListAdapter3);
        binding.rlvList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getGoodsListModel(false);
            }

            @Override
            public void onLoadMore() {
                viewModel.getGoodsListModel(true);
            }
        });
        goodsListAdapter3.setOnItemClick(new AdapterOnItemClick<GoodsListEntity3>() {
            @Override
            public void onItemClick(GoodsListEntity3 goodsListEntity3, int position) {
                if (goodsListEntity3.getCid1().equals("7")) {
                    STDetailActivity.start(GoodsListActivity3.this, goodsListEntity3.getId());
                } else {
                    if (!"草稿".equals(goodsListEntity3.getStatus())) {
                        GoodsDetailActivity.start(GoodsListActivity3.this, goodsListEntity3.getId());
                    }
                }
            }
        });
        goodsListAdapter3.setItemCallBack(new GoodsListAdapter3.ItemCallBack() {
            @Override
            public void up(String id) {
                getGoodsIds(OPT_UP, id);
            }

            @Override
            public void down(String id) {
                getGoodsIds(OPT_DOWN, id);
            }

            @Override
            public void del(String id) {
                getGoodsIds(OPT_DEL, id);
            }
        });
        allWindow4 = new DictWindow4(GoodsListActivity3.this);
        allWindow4.setOnCallBack(new DictWindow4.OnCallBack() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void result(DictEntity3 dictEntity) {
                allChecked = dictEntity.getName();
                binding.allView.setText(allChecked);
                viewModel.status.set(dictEntity.getId());
                viewModel.getGoodsListModel(false);
            }
        });
        allWindow4.setOnCloseBack(new DictWindow4.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.allArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
                binding.allView.setTextColor(getResources().getColor(R.color.color_black_ff666666));
            }
        });
        categoryPopWindow3 = new CategoryPopWindow3(GoodsListActivity3.this);
        categoryPopWindow3.setOnResultCallBack(new BasePopWindow.OnResultCallBack<String>() {
            @Override
            public void result(String result) {
                viewModel.cid3.set(result);
                viewModel.getGoodsListModel(false);
            }
        });
        categoryPopWindow3.setOnCloseBack(new DictWindow3.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.typeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
                binding.classTv.setTextColor(getResources().getColor(R.color.color_black_ff666666));
            }
        });
    }

    @Override
    protected void init() {
//        viewModel.getGoodsListModel(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        viewModel.getGoodsListModel(false);
    }

    public void showList(List<GoodsListEntity3> datas, boolean isLoadMore) {
        if (isLoadMore) {
            binding.rlvList.loadMoreComplete();
            if (datas.size() != 0) {
                goodsListAdapter3.addDatas(datas);
            }
        } else {
            if (datas.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }
            binding.rlvList.refreshComplete();
            binding.rlvList.setLoadingMoreEnabled(true);
            goodsListAdapter3.setDatas(datas);
        }
    }

    public void showAllPopWindow(List<DictEntity3> data) {
        this.allDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        allChecked = data.get(0).getName();
        allWindow4.setData(data);
        allWindow4.setCheckDefault(allChecked);
    }

    public void showCategoryView(List<MenuEntity<MenuEntity<MenuEntity>>> datas) {
        if (datas == null) {
            return;
        }
        this.categoryList = datas;
        categoryPopWindow3.setDatas(datas);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_view:
                if (binding.editView.getText().toString().equals("批量")) {
                    finish();
                } else {
                    binding.editView.setText("批量");
                    binding.editLayout.setVisibility(View.GONE);
                    binding.normalLayout.setVisibility(View.VISIBLE);
                    binding.titleView.setVisibility(View.GONE);
                    binding.editSearch.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.right_view:
                Intent intent = new Intent(GoodsListActivity3.this, AddGoodsActivity.class);
                startActivity(intent);
                break;
            case R.id.all_layout://类型
                binding.allArrowView.setImageResource(R.mipmap.icon_up_red);
                binding.allView.setTextColor(getResources().getColor(R.color.color_main));
                allWindow4.setCheckDefault(allChecked);
                allWindow4.showPopwindow(binding.allLayout);
                if (allDictEntityList == null) {
                    viewModel.getGoodsAllModel();
                }
                break;
            case R.id.type_layout://
                binding.typeArrowView.setImageResource(R.mipmap.icon_up_red);
                binding.classTv.setTextColor(getResources().getColor(R.color.color_main));
                categoryPopWindow3.showPopwindow(binding.typeLayout);
                if (categoryList == null) {
                    viewModel.getGoodsCategoryModel();
                }
                break;
            case R.id.edit_view:
                if (binding.editView.getText().toString().equals("批量")) {
                    binding.editView.setText("完成");
                    binding.normalLayout.setVisibility(View.GONE);
                    binding.editLayout.setVisibility(View.VISIBLE);
                    binding.editSearch.setVisibility(View.GONE);
                    binding.titleView.setVisibility(View.VISIBLE);
                } else {
                    binding.editView.setText("批量");
                    binding.editLayout.setVisibility(View.GONE);
                    binding.normalLayout.setVisibility(View.VISIBLE);
                    binding.titleView.setVisibility(View.GONE);
                    binding.editSearch.setVisibility(View.VISIBLE);
                    viewModel.getGoodsListModel(false);
                }
                break;
            case R.id.add_layout:
                int type = ACAdminDialogUtils.isPermission(ACAdminDialogUtils.MK_ADDCOMMODITY, true);
                if (type == ACAdminDialogUtils.TYPE_NORMAL) {
                    GoodsPublishActivity.start(GoodsListActivity3.this);
                } else {
                    ACAdminDialogUtils.showACDialog(type, this);
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGoodsEvent(GoodsEvent event) {
        if (event.getMessageTag() == EVENT_GOODS_PUBLISH_NO_ID) {
            viewModel.getGoodsListModel(false);
        } else if (event.getMessageTag() == EVENT_GOODS_PUBLISH) {
            viewModel.getGoodsListModel(false);
        }
    }

    private void getGoodsIds(String opt, String id) {
        List<String> goodsIds = new ArrayList<>();
        goodsIds.add(id);
        if (opt.equals(OPT_UP)) {
            String msg = "商品上架后，则可进行下单购\n买，确认要上架吗？";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        } else if (opt.equals(OPT_DOWN)) {
            String msg = "商品下架后，则无法进行购\n买，确认下架吗？";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        } else if (opt.equals(OPT_DEL)) {
            String msg = "删除后不可恢复，请谨慎操作";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        }
    }

    public void showOptSuccess(String opt, int size) {
        String msg = "";
        if (opt.equals(OPT_UP)) {
            msg = "上架成功";
        } else if (opt.equals(OPT_DOWN)) {
            msg = "下架成功";
        } else if (opt.equals(OPT_DEL)) {
            msg = "删除成功";
        }
        MToast.showToast(getActivity(), msg);
        viewModel.getGoodsListModel(false);
    }
}

